<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class BackupDatabaseCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'database:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    private $allDataTables = 'Back up all data tables';

    private $tableClass = [];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $database = $this->ask('Please enter the name of the database to be backed up');
        if (empty($database)) {
            return $this->handle();
        }
        $rowTables = DB::select('show tables');
        $database = 'Tables_in_' . $database;
        foreach ($rowTables as $table) {
            $tables[] = $table->$database;
        }
        $tables[] = $this->allDataTables;
        $table = $this->choice(
            'Please select the data table you want to backup',
            $tables,
            0,
            null,
            true
        );
        if (in_array($this->allDataTables, $table)) {
            array_pop($tables);
        } else {
            $tables = $table;
        }
        if (empty($tables)) {
            return false;
        }
        foreach ($tables as $table) {
            $class = $table . '_seeder::class';
            array_push($this->tableClass, $class);
            $this->call('make:seeder2', [
                'name' => $table . '_seeder',
                '--force' => true,
            ]);
        }
        $replaceStr = $this->formatDatas($this->tableClass);
        $this->info('The database has been backed up. Please add the following contents to the [DatabaseSeeder] file:' . PHP_EOL . $replaceStr);
    }

    protected function formatDatas($importDatas)
    {
        $replaceStr = '';
        $replaceStr .= PHP_EOL;
        foreach ($importDatas as $key => $value) {
            $replaceStr .= "\t" . $value . "," . PHP_EOL;
        }
        $replaceStr .= PHP_EOL;
        return $replaceStr;
    }
}
